//
//  ListViewController.m
//  JXPagerViewExample-OC
//
//  Created by jiaxin on 2019/12/30.
//  Copyright © 2019 jiaxin. All rights reserved.
//

#import "XMHomeListViewController.h"
#import "XMHomeListTableViewCell.h"

@interface XMHomeListViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic, strong) NSMutableArray <XMUserModel *> *dataArray;
@property (nonatomic, copy) NSString *requestUrl;
@property (nonatomic, assign) NSInteger page;

@end

@implementation XMHomeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initVariables];
    [self setupSubviews];
    [self homeListData];
    [self setupRefresh];
}

#pragma mark - 初始化变量
- (void)initVariables {
    self.dataArray = [NSMutableArray array];
    self.page = 1;
    self.requestUrl = self.type == 0 ? @"api/index/sift" : @"api/index/new";
    [kNotificationCenter addObserver:self selector:@selector(homeListDataRefresh) name:@"homeListDataRefresh" object:nil];
}

#pragma mark - setupSubViews
- (void)setupSubviews {
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.tableView registerNib:kNibWithName(kStringFromClass(XMHomeListTableViewCell)) forCellReuseIdentifier:kStringFromClass(XMHomeListTableViewCell)];
    
    //列表的contentInsetAdjustmentBehavior失效，需要自己设置底部inset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.view addSubview:self.tableView];
}

#pragma mark - refresh
- (void)setupRefresh {
    XMWeakSelf(self);
    self.tableView.mj_header = [XMRefreshNormalHeader headerWithRefreshingBlock:^{
        XMStrongSelf(self);
        [self homeListDataRefresh];
    }];
    self.tableView.mj_footer = [XMRefreshBackFooter footerWithRefreshingBlock:^{
        XMStrongSelf(self);
        self.page += 1;
        [self homeListData];
    }];
    self.tableView.mj_footer.hidden = YES;
}

- (void)homeListDataRefresh {
    self.page = 1;
    [self.dataArray removeAllObjects];
    [self homeListData];
}

- (void)homeListData {
    NSMutableDictionary *dic = @{
        @"page_no": @(self.page),
        @"page_size": @(10),
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:self.requestUrl parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        [self.tableView hideStatusView];
        if (tip.success) {
            [MBProgressHUD hideHUD];
            NSArray *record = [result safe_objectForKey:@"record"];
            NSArray *array = [XMUserModel mj_objectArrayWithKeyValuesArray:record];
            [self.dataArray addObjectsFromArray:array];
            if (self.dataArray.count == 0) {
                [self.tableView showStatusView:(YHViewStatusTypeEmptyData)];
                self.tableView.statusTitleLabel.text = @"还没有用户哦~";
            }
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        if (tip.loadMore) {
            [self.tableView.mj_footer endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.frame = self.view.bounds;
}

#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMHomeListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMHomeListTableViewCell) forIndexPath:indexPath];
    XMUserModel *model = [self.dataArray safe_objectAtIndex:indexPath.row];
    cell.model = model;
    XMWeakSelf(self);
    cell.chatBlock = ^{
        XMStrongSelf(self);
        if (self.chatBlock) {
            self.chatBlock(model);
        }
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 84;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    XMUserModel *model = [self.dataArray safe_objectAtIndex:indexPath.row];
    if (self.detailBlock) {
        self.detailBlock(model);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.scrollCallback ?: self.scrollCallback(scrollView);
}

#pragma mark - JXPagingViewListViewDelegate

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.tableView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}

- (void)listWillAppear {
//    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidAppear {
//    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listWillDisappear {
//    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidDisappear {
//    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)dealloc {
    NSLog(@"ListViewController dealloced");
}

@end
